<template>
  <div class="p-4">
    <!-- Search Form -->
    <el-card>
      <el-form :model="searchForm" label-width="100px" inline>
        <el-form-item label="报工类型">
          <el-select v-model="searchForm.feedbackType" clearable placeholder="请选择报工类型" style="width: 200px;">
            <el-option label="自行报工" value="SELF"/>
            <el-option label="统一报工" value="UNI"/>
          </el-select>
        </el-form-item>
        <el-form-item label="工作站名称">
          <el-input v-model="searchForm.workstationName" clearable placeholder="请输入工作站名称"/>
        </el-form-item>
        <el-form-item label="生产工单号">
          <el-input v-model="searchForm.workorderCode" clearable placeholder="请输入生产工单号"/>
        </el-form-item>
        <el-form-item label="产品物料编码">
          <el-input v-model="searchForm.itemCode" clearable placeholder="请输入产品物料编码"/>
        </el-form-item>
        <el-form-item label="产品物料名称">
          <el-input v-model="searchForm.itemName" clearable placeholder="请输入产品物料名称"/>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" clearable placeholder="请选择状态" style="width: 200px;">
            <el-option label="已完成" value="FINISHED"/>
            <el-option label="审批中" value="APPROVING"/>
            <el-option label="草稿" value="PREPARE"/>
            <el-option label="已拒绝" value="REFUSE"/>
          </el-select>
        </el-form-item>
        <el-button type="primary" @click="handleSearch">
          <el-icon>
            <Search/>
          </el-icon>
          搜索
        </el-button>
        <el-button @click="handleReset">
          <el-icon>
            <Refresh/>
          </el-icon>
          重置
        </el-button>
      </el-form>
    </el-card>
    <el-card style="margin-top: 20px">
      <!-- Action Buttons -->
      <div class="flex">
        <el-button type="primary" size="small" @click="handleAdd">
          <el-icon>
            <Plus/>
          </el-icon>
          新增
        </el-button>
        <el-button type="danger" size="small" @click="handleDelete">
          <el-icon>
            <Delete/>
          </el-icon>
          删除
        </el-button>
      </div>

      <!-- Data Table -->
      <el-table ref="multipleTable" :data="tableData" border style="width: 100%" height="380px"
                max-height="380px" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55"/>
        <el-table-column prop="reportType" label="报工类型" width="120px">
          <template #default="scope">
            <span>{{ scope.row.feedbackType == "SELF" ? "自行报工" : "统一报工" }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="workstationName" label="工作站" width="120px"/>
        <el-table-column prop="workorderCode" label="生产工单号" width="150px"/>
        <el-table-column prop="itemCode" label="产品物料编码" width="120px"/>
        <el-table-column prop="itemName" label="产品物料名称" width="120px"/>
        <el-table-column prop="specification" label="规格型号" width="120px"/>
        <el-table-column prop="quantityFeedback" label="报工数量" width="120px"/>
        <el-table-column prop="nickName" label="报工人" width="120px"/>
        <el-table-column prop="feedbackTime" label="报工时间" width="120px"/>
        <el-table-column prop="recordNick" label="审核人" width="100px"/>
        <el-table-column prop="status" fixed="right" width="100px" label="状态">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">{{ getStatusName(scope.row.status) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="150">
          <template #default="scope">
            <el-button type="primary" link @click="handleUpdate(scope.row,1)">查看</el-button>
            <el-button type="primary" link @click="handleUpdate(scope.row)" v-if="scope.row.status === 'PREPARE'">
              修改
            </el-button>
            <el-button type="danger" link @click="handleDelete(scope.row)" v-if="scope.row.status === 'PREPARE'">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- Pagination -->
      <div class="justify-between">
        <el-pagination
            :current-page="currentPage"
            :page-size="pageSize"
            :page-sizes="[10, 20, 30, 50]"
            layout="sizes, prev, pager, next"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    <add-feedback :visible="addFeedback" @close="CloseDialog"/>
    <UpdateFeedback :visible="updateFeedback" :data="multipleSelection" :updateStatus="updateStatus"
                    @close="CloseDialog"/>
  </div>
</template>

<script setup>
import {onMounted, reactive, ref} from 'vue'
import {Delete, Plus, Refresh, Search} from '@element-plus/icons-vue'
import AddFeedback from "@/components/ProductionReport/AddDialog.vue"
import {deleteFeedback, findFeedback} from "@/apis/zyj/feedback.js";
import {ElMessage, ElMessageBox} from "element-plus";
import UpdateFeedback from "@/components/ProductionReport/UpdateDialog.vue"

const updateFeedback = ref(false)
const addFeedback = ref(false)
const pageSize = ref(10)
const currentPage = ref(1)
const total = ref(0)

const select_order_number = ref('') //表格select选中的条数
const select_orderId = ref([]) //表格select复选框选中的id
const multipleSelection = ref()//选中行的数据
const multipleTable = ref()//用于表格多选框选中的清理

const updateStatus = ref('修改')

const CloseDialog = () => {
  addFeedback.value = false
  updateFeedback.value = false
  initData()
}

function initData() {
  searchForm.pageSize = pageSize.value
  searchForm.currentPage = currentPage.value
  findFeedback(searchForm).then(res => {
    console.log(res)
    tableData.value.length = 0
    tableData.value = res.records
    total.value = res.total
    currentPage.value = res.current
    pageSize.value = res.size
  })
}

onMounted(() => {
  initData();
})


// Search form
const searchForm = reactive({
  feedbackType: '',
  workstationName: '',
  workorderCode: '',
  itemCode: '',
  itemName: '',
  status: '',
})

// Table data
const tableData = ref([])

// Methods
const handleSearch = () => {
  initData()
}

const handleReset = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = ''
  })
  initData()
}

const handleAdd = () => {
  addFeedback.value = true
}

const handleUpdate = (row, type) => {
  if (type == 1) {
    updateStatus.value = '查看'
  } else {
    updateStatus.value = '修改'
  }
  console.log(updateStatus.value)
  multipleSelection.value = {...row}
  updateFeedback.value = true
}


const handleDelete = (row) => {
  if (row.recordId != null) {
    select_order_number.value = "1";
  } else {
    select_order_number.value = multipleSelection.value.length;
  }
  ElMessageBox.confirm(
      '是否要删除 ' + select_order_number.value + '条数据',
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
  )
      .then(() => {
        if (row.recordId != null) {
          select_orderId.value = [];
          select_orderId.value.push(row.recordId)
        }
        deleteFeedback(select_orderId.value).then((res) => {
          if (res == '成功') {
            initData()
            ElMessage.success('成功删除: ' + select_order_number.value + '条数据')
            select_order_number.value = 0;
            select_orderId.value = [];
            multipleTable.value.clearSelection();
          } else {
            ElMessage.error('系统错误！删除失败')
          }
        })
      })
      .catch(() => {
        ElMessage.info('删除取消')
      })
}

//选中事件
const handleSelectionChange = (val) => {
  // 解决来回切换页面，也无法清除上次选中情况
  multipleSelection.value = val;
  select_order_number.value = multipleSelection.value.length;
  select_orderId.value = [];
  if (val) {
    val.forEach((row) => {
      if (row) {
        select_orderId.value.push(row.recordId);
      }
    });
  }
}

const getStatusType = (status) => {
  switch (status) {
    case 'FINISHED':
      return 'success'
    case 'APPROVING':
      return 'warning'
    case 'PREPARE':
      return 'info'
    case 'REFUSE':
      return 'error'
    default:
      return ''
  }
}
const getStatusName = (status) => {
  switch (status) {
    case 'FINISHED':
      return '已完成'
    case 'APPROVING':
      return '审批中'
    case 'PREPARE':
      return '草稿'
    case 'REFUSE':
      return '已拒绝'
    default:
      return ''
  }
}

const handleSizeChange = (val) => {
  pageSize.value = val
  handleSearch()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  handleSearch()
}
</script>

<style scoped>
.flex {
  margin-bottom: 20px;
}

:deep(.el-form-item__label) {
  font-weight: 500;
}

:deep(.el-table th) {
  background-color: #f5f7fa;
  color: #606266;
}

.justify-between {
  margin: 20px 0;
  display: flex;
  float: right;
}
</style>